/* eslint-disable regexp/no-super-linear-backtracking */
import fs from 'node:fs';
import readline from 'node:readline';

function getTopology() {
  const ri = readline.createInterface(
    fs.createReadStream(
      'D:/exp-data/ibdiagnet2/ibdiagnet2/ibdiagnet2.ibnetdiscover',
    ),
  );
  const topo = {
    nodes: {},
    edges: [],
  };
  let guid = '';
  ri.on('line', (line) => {
    if (line.startsWith('Switch') || line.startsWith('Ca')) {
      // Switch  65 "S-fc6a1c03009b0180"      # "SHLG-PSC-ZS3F1-POD1-JQ1-CS-HJ-ZONE2-1/1" base port 0 lid 2015 lmc 0
      const [_, _guid, name] = /.*-(.*)".*"(.*)"/.exec(line);
      // const [_, _guid, name, lid] = /.*-(.*)".*"(.*)".*lid (.*) lmc/.exec(line);
      // const [_1, _2, _guid, _3, name, _4, _5, _6, _7, lid] =
      // line.split(/[\s"S-]+/);
      if (name.startsWith('Mellanox Technologies')) {
        // ignore virtual port
        return;
      }
      guid = _guid;
      const node = {
        id: guid,
        name,
        type: line.startsWith('Ca') ? 'ca' : 'switch',
      };
      topo.nodes[guid] = node;
    }
    if (line.startsWith('[')) {
      const [_, p1, target, p2] = /\[(.*?)\].*-(.*)"\[(.*?)\]/.exec(line);
      if (p1 === '65' || p2 === '65') {
        // ignore the virtual ports of switches
        return;
      }
      const edge = {
        source: guid,
        target,
        p1,
        p2,
      };
      topo.edges.push(edge);
    }
  });
  return topo;
}

function getNodes() {
  const ri = readline.createInterface({
    crlfDelay: Infinity,
    input: fs.createReadStream(
      'D:/exp-data/ibdiagnet2/ibdiagnet2/ibdiagnet2.lst',
    ),
  });
  const nodes = {};
  ri.on('line', (line) => {
    if (line.startsWith('{ CA')) {
      // { CA Ports:01 SystemGUID:58a2e1030005ee3c NodeGUID:58a2e1030005ee3c PortGUID:58a2e1030005ee3c VenID:000002c9 DevID:1021 Rev:00000000 {SHLG-PSC-ZS3F1-SPOD-PM-OS07-CLUSTER-ZS-476 mlx5_1} LID:14b8 PN:01 }
      const [_, _guid, name, lid, vendorId] = line.match(
        /SystemGUID:([0-9a-fA-F]+).*?\{([^}]+)\}.*?LID:([0-9a-fA-F]+).*?VenID:([0-9a-fA-F]+)/,
      );
      // console.log(_guid, name, lid);
      nodes[_guid] = {
        name,
        lid,
        vendorId,
      };
    }
  });
  return nodes;
}

const nodes = getNodes();

const topo = getTopology();

export default eventHandler(async (event) => {
  const q = getQuery(event);
  if (q.id) {
    return useResponseSuccess(nodes[q.id]);
  }
  return useResponseSuccess(topo);
});

// export default eventHandler(async (event) => {
//   // const userinfo = verifyAccessToken(event);
//   // if (!userinfo) {
//   //   return unAuthorizedResponse(event);
//   // }

//   await sleep(600);

//   const { page, pageSize, sortBy, sortOrder } = getQuery(event);
//   const listData = structuredClone(mockData);
//   if (sortBy && Reflect.has(listData[0], sortBy as string)) {
//     listData.sort((a, b) => {
//       if (sortOrder === 'asc') {
//         if (sortBy === 'price') {
//           return (
//             Number.parseFloat(a[sortBy as string]) -
//             Number.parseFloat(b[sortBy as string])
//           );
//         } else {
//           return a[sortBy as string] > b[sortBy as string] ? 1 : -1;
//         }
//       } else {
//         if (sortBy === 'price') {
//           return (
//             Number.parseFloat(b[sortBy as string]) -
//             Number.parseFloat(a[sortBy as string])
//           );
//         } else {
//           return a[sortBy as string] < b[sortBy as string] ? 1 : -1;
//         }
//       }
//     });
//   }
//   return useResponseSuccess(listData);
//   return usePageResponseSuccess(page as string, pageSize as string, listData);
// });
